﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BadOCR.Runtime
{
    public class UserConfig
    {
        public static string MainFolder
        {
            get
            {
                var mainFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "BadOCR");
                Directory.CreateDirectory(mainFolder);
                return mainFolder;
            }
        }

        public OCREngineKind OCREngineKind { get; set; } = OCREngineKind.Sougou;

        public string ClientId { get; set; }

        public string ClientSecret { get; set; }

        //public string ApiKey { get; set; }

        public bool AutoSave { get; set; }

        public LanguageKind MotherLanguage { get; set; } = LanguageKind.SimplifiedChinese;

        public LanguageKind FirstForeignLanguage { get; set; } = LanguageKind.English;

        private UserConfig() { }

        public static UserConfig Current;

        static UserConfig()
        {
            Current = new UserConfig();

            // 读取配置文件 => JToken
            var configFilePath = Path.Combine(MainFolder, "config.json");
            if (!File.Exists(configFilePath))
                return;
            var userConfigJson = JToken.Parse(File.ReadAllText(configFilePath));

            // 装载到Current中
            Current.OCREngineKind = (OCREngineKind)userConfigJson.Value<int>(nameof(OCREngineKind));
            if (Current.OCREngineKind == OCREngineKind.Baidu)
            {
                Current.ClientId = userConfigJson.Value<string>(nameof(ClientId));
                Current.ClientSecret = userConfigJson.Value<string>(nameof(ClientSecret));
            }

            Current.MotherLanguage = (LanguageKind)userConfigJson.Value<int>(nameof(MotherLanguage));
            Current.FirstForeignLanguage = (LanguageKind)userConfigJson.Value<int>(nameof(FirstForeignLanguage));

            if (userConfigJson["AutoSave"] != null)
                Current.AutoSave = userConfigJson.Value<bool>(nameof(AutoSave));
        }

        public void Save()
        {
            // 持久化到硬盘文件
            File.WriteAllText(
                Path.Combine(MainFolder, "config.json"),
                JsonConvert.SerializeObject(new
                {
                    OCREngineKind,
                    ClientId,
                    ClientSecret,

                    MotherLanguage,
                    FirstForeignLanguage,
                    AutoSave
                })
            );
        }
    }   
}
